package gripper.ftp.handle;

import java.io.BufferedReader;
import java.io.File;
import java.io.IOException;
import java.io.OutputStream;

import gripper.ftp.FtpSession;
import gripper.ftp.PathConvert;

public class SIZEHandle implements Handle {
	FtpSession ftpSession;

	public SIZEHandle(FtpSession ftpSession) {
		this.ftpSession = ftpSession;
	}

	public void process(String line, BufferedReader br, OutputStream os) throws IOException {
		String[] splited = line.split(" ");
		if (splited == null || splited.length < 2) {
			os.write("550 requested action aborted.\r\n".getBytes());
			os.flush();
			return;
		}
		String fileName = splited[1].trim();
		fileName = ftpSession.currentDir + "/" + fileName;
		fileName = PathConvert.toServerPath(ftpSession.getRootDir(), fileName);
		File file = new File(fileName);
		if (!file.exists()) {
			os.write("550 requested action aborted. file not exists.\r\n".getBytes());
			os.flush();
			return;
		}
		if (file.isDirectory()) {
			os.write(("213 0").getBytes());
			os.flush();
			return;
		}
		os.write(("213 " + file.length()).getBytes());
		os.flush();
	}
}
